package net.documentshare.docu;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 数据存储对象
 * @author 李岩飞
 *
 */
public class DatabaseBean {
	private final Map<String, String> databaseMap = new LinkedHashMap<String, String>();//数据存储目录
	private int diskSpace = 500;//500M的时候换目录
	private String currentKey = null;//当前目录, 保存的是key=d1
	private String rar = "";

	public void setRar(String rar) {
		this.rar = rar;
	}

	public String getRar() {
		return rar;
	}

	public Map<String, String> getDatabaseMap() {
		return databaseMap;
	}

	/**
	 * 当key=null是，表示采用默认的磁盘路径,既web服务器下
	 * @param key
	 * @param value
	 */
	public void addDatabase(final String key, String value) {
		value = value + DocuUtils.$data$;
		if (checkFilePath(key, value)) {
			if (key == null) {
				this.databaseMap.put("d0", value);
			} else {
				this.databaseMap.put(key, value);
			}
		}
	}

	/**
	 * 检查路径
	 * @param path
	 * @return
	 */
	private boolean checkFilePath(final String key, final String path) {
		final File file = new File(path);
		if (file.isFile()) {
			return false;
		}
		if (!file.exists()) {
			file.mkdirs();
		}
		//设置当前目录
		if (file.getFreeSpace() / 1024 / 1024 > diskSpace && this.currentKey == null) {
			this.currentKey = key;
		}
		return true;
	}

	public void setDiskSpace(int diskSpace) {
		this.diskSpace = diskSpace;
	}

	public void setCurrentKey(String currentDir) {
		this.currentKey = currentDir;
	}

	public String getCurrentKey() {
		return currentKey;
	}

	public String getDatabase(final String key) {
		return this.databaseMap.get(key);
	}

	/**
	 * 返回可用磁盘Key
	 * @return
	 */
	public String getUsableDatabase() {
		if (new File(getDatabase(currentKey)).getFreeSpace() / 1024 / 1024 > diskSpace) {
			return currentKey;
		}
		for (final String key : this.databaseMap.keySet()) {
			if (new File(this.databaseMap.get(key)).getFreeSpace() / 1024 / 1024 > diskSpace) {
				this.currentKey = key;
				break;
			}
		}
		return currentKey;
	}

}
